<template>
  <div class="user-settings-container">
    <div class="settings-card">
      <!-- 返回按钮 -->
      <div class="close-btn" @click="router.go(-1)">
        <el-icon><Close /></el-icon>
      </div>
      
      <h2 class="settings-title">个人信息设置</h2>
      
      <!-- 头像上传 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <img :src=" defaultAvatar" class="avatar" alt="用户头像">
          <div class="avatar-edit" >
            <el-icon><CameraFilled /></el-icon>
          </div>
        </div>
        <input 
          type="file" 
          ref="fileInput" 
          accept="image/*" 
          style="display: none" 
         
        >
        <p class="avatar-hint">点击头像可更换 (支持JPG/PNG)</p>
      </div>

      <!-- 表单区域 -->
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-position="top" 
        class="settings-form"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入新用户名"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码修改 -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="form.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
          <div class="password-strength" :class="passwordStrengthClass">
            {{ passwordStrengthText }}
          </div>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="form.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitting"
            class="submit-btn"
          >
            保存更改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { CameraFilled, User, Lock, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { updateuserifm } from '@/api/Update_user-information'
const router = useRouter()
const userStore = useUserStore()

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 表单数据
const form = ref({
  username: '',
  newPassword: '',
  confirmPassword: ''
})

// 初始化表单数据
onMounted(() => {
  form.value.username = userStore.username || '甲骨文爱好者'
})

// 头像相关
const fileInput = ref(null)
const avatarPreview = ref('')
const avatarFile = ref(null)

// 表单引用
const formRef = ref(null)
const submitting = ref(false)



// // 触发文件选择
// const triggerFileInput = () => {
//   fileInput.value.click()
// }

// // 处理头像更改
// const handleAvatarChange = (e) => {

//   const file = e.target.files[0]
//   if (!file) return

//   // 检查文件类型
//   const allowedTypes = ['image/jpeg', 'image/png']
//   if (!allowedTypes.includes(file.type)) {
//     ElMessage.error('仅支持 JPG/PNG 格式的图片')
//     return
//   }

//   // 检查文件大小 (限制5MB，与文档一致)
//   if (file.size > 5 * 1024 * 1024) {
//     ElMessage.error('图片大小不能超过5MB')
//     return
//   }

//   // 预览图片
//   const reader = new FileReader()
//   reader.onload = (e) => {
//     avatarPreview.value = e.target.result
//     avatarFile.value = file
//   }
//   reader.readAsDataURL(file)
// }

// 密码强度计算
const passwordStrength = computed(() => {
  if (!form.value.newPassword) return 0
  
  let strength = 0
  const password = form.value.newPassword
  
  // 长度加分
  if (password.length >= 8) strength++
  if (password.length >= 12) strength++
  
  // 复杂度加分
  if (/[A-Z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[^A-Za-z0-9]/.test(password)) strength++
  
  return Math.min(strength, 4)
})

// 密码强度文本和样式
const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value
  const texts = ['非常弱', '弱', '中等', '强', '非常强']
  return `密码强度: ${texts[strength]}`
})

const passwordStrengthClass = computed(() => {
  return `strength-${passwordStrength.value}`
})

// 表单验证规则
const validatePassword = (rule, value, callback) => {
  if (value && value.length < 8) {
    callback(new Error('密码长度不能少于8位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '用户名长度在1到16个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      // 创建 FormData 对象 (multipart/form-data)
      const formData = new FormData()
      
      // 添加表单数据
      if (form.value.username) {
        formData.append('userName', form.value.username)
      }
      
      if (form.value.newPassword) {
        formData.append('newPassword', form.value.newPassword)
      }
      
      // // 如果有新头像
      // if (avatarFile.value) {
      //   formData.append('file', avatarFile.value)
      // }
       
      const newifm = await updateuserifm(formData)

      if(newifm.userName)
     {
       userStore.setUsername(newifm.userName)
       console.log(newifm.userName)
     }
      ElMessage.success('个人信息更新成功')
    if(form.value.newPassword)
     {
        userStore.logout()
        router.push({
         name: 'Login',
          query: { fromLogout: true }  // 修正拼写
        })
    ElMessage.success('密码修改成功，请重新登录')
     }
     
    } catch (error) {
      ElMessage.error('更新失败: ' + (error.message || '未知错误'))



    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  form.value.username = userStore.username || ''
  // avatarPreview.value = ''
  avatarFile.value = null
}
</script>

<style scoped lang="scss">
/* 全局变量 */
$primary-color: #8B4513;
$secondary-color: #d4a373;
$light-bg: #fffaf5;
$border-color: #e7d9c8;

.user-settings-container {
  max-width: 640px;
  margin: 2rem auto;
  padding: 0 2rem;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 4rem);
}

.settings-card {
  position: relative;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(139, 69, 19, 0.1);
  padding: 2.5rem;
  border: 1px solid $border-color;
  width: 100%;
  transition: all 0.3s ease;
}

.close-btn {
  position: absolute;
  top: 1.5rem;
  right: 1.5rem;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: $primary-color;
  transition: all 0.3s ease;
  font-size: 1.25rem;
  background: rgba(139, 69, 19, 0.05);
  
  &:hover {
    background-color: rgba(139, 69, 19, 0.1);
    color: $secondary-color;
    transform: scale(1.1);
  }
}

.settings-title {
  text-align: center;
  color: $primary-color;
  margin: 0.5rem 0 2rem;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2rem;
}

.avatar-wrapper {
  position: relative;
  width: 8rem;
  height: 8rem;
  margin-bottom: 1rem;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid $border-color;
  box-shadow: 0 4px 12px rgba(139, 69, 19, 0.15);
  transition: all 0.3s ease;
  
  &:hover {
    border-color: $secondary-color;
  }
}

.avatar-edit {
  position: absolute;
  right: 0;
  bottom: 0;
  background: $primary-color;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  
  &:hover {
    background: $secondary-color;
    transform: scale(1.1);
  }
}

.avatar-hint {
  color: #a38b76;
  font-size: 0.875rem;
  margin-top: 0.5rem;
  text-align: center;
}

.settings-form {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: $primary-color;
  font-weight: 500;
  padding-bottom: 0.5rem;
  font-size: 0.9375rem;
}

:deep(.el-input__wrapper) {
  background-color: $light-bg;
  border: 1px solid $border-color;
  border-radius: 8px;
  box-shadow: none;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input__wrapper.is-focus) {
  border-color: $secondary-color;
  box-shadow: 0 0 0 1px $secondary-color;
}

.password-strength {
  margin-top: 0.5rem;
  font-size: 0.8125rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  display: inline-block;
  transition: all 0.3s ease;
}

.strength-0 {
  color: #ff4d4f;
  background-color: #fff2f0;
}

.strength-1 {
  color: #fa8c16;
  background-color: #fff7e6;
}

.strength-2 {
  color: #faad14;
  background-color: #fffbe6;
}

.strength-3 {
  color: #52c41a;
  background-color: #f6ffed;
}

.strength-4 {
  color: #389e0d;
  background-color: #f6ffed;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
  gap: 1.5rem;
}

.submit-btn {
  background-color: $primary-color;
  border-color: $primary-color;
  min-width: 8rem;
  height: 2.75rem;
  font-size: 1rem;
  transition: all 0.3s ease;
  
  &:hover {
    background-color: $secondary-color;
    border-color: $secondary-color;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(139, 69, 19, 0.2);
  }
  
  &:active {
    transform: translateY(0);
  }
}




@media (min-width:2300px) {

  /* 标签文字 */
  :deep(.el-form-item__label) {
    font-size: 1.1rem !important;
    padding-bottom: 0.75rem;
  }
  
  /* 输入文字 */
  :deep(.el-input__inner) {
    font-size: 1.1rem !important;
  }
  
  /* 提示文字 */
  .avatar-hint {
    font-size: 1rem;
  }
  
  /* 按钮文字 */
  .form-actions .el-button {
    font-size: 1.1rem;
  }

  .user-settings-container {
    max-width: 780px;
    min-height: calc(100vh - 4rem);  // 减少减去的值使容器更高
    margin: 4rem auto;  // 增加外边距
    padding: 2rem 0;   // 增加上下内边距
  }
  
  .settings-card {
    padding: 4rem;  // 增加内边距
    min-height: 800px; // 设置最小高度
  }

  .avatar-wrapper {
    width: 11rem;  // 进一步增加尺寸
    height: 11rem;
    margin-bottom: 2rem;
  }
  
  .avatar-edit {
    width: 4rem;
    height: 4rem;
  }
  
  .settings-title {
    font-size: 2rem;  // 增大标题
    margin-bottom: 3rem;
  }
  
  .form-actions {
    margin-top: 3rem;
  }
}

@media (min-width: 1920px) and (max-width: 2300px) {

  :deep(.el-form-item__label) {
    font-size: 1.05rem !important;
    padding-bottom: 0.65rem;
  }
  
  :deep(.el-input__inner) {
    font-size: 1.05rem !important;
  }
  
  .avatar-hint {
    font-size: 0.95rem;
  }
  
  .form-actions .el-button {
    font-size: 1.05rem;
  }

  .user-settings-container {
    max-width: 730px;
    min-height: calc(100vh - 3rem);
    margin: 3rem auto;
    padding: 1.5rem 0;
  }
  
  .settings-card {
    padding: 3.5rem;
    min-height: 700px;
  }

  .avatar-wrapper {
    width: 10rem;
    height: 10rem;
    margin-bottom: 1.75rem;
  }
  
  .avatar-edit {
    width: 3.5rem;
    height: 3.5rem;
  }
  
  .settings-title {
    font-size: 1.75rem;
    margin-bottom: 2.75rem;
  }
  
  .form-actions {
    margin-top: 2.5rem;
  }
}

@media (min-width: 1751px) and (max-width: 1919px) {

  :deep(.el-form-item__label) {
    font-size: 1rem !important;
    padding-bottom: 0.6rem;
  }
  
  :deep(.el-input__inner) {
    font-size: 1rem !important;
  }
  
  .avatar-hint {
    font-size: 0.9rem;
  }
  
  .form-actions .el-button {
    font-size: 1rem;
  }


  .user-settings-container {
    max-width: 680px;
    min-height: calc(100vh - 2.5rem);
    margin: 2.5rem auto;
    padding: 1.25rem 0;
  }
  
  .settings-card {
    padding: 3rem;
    min-height: 650px;
  }

  .avatar-wrapper {
    width: 9rem;
    height: 9rem;
    margin-bottom: 1.5rem;
  }
  
  .avatar-edit {
    width: 3.25rem;
    height: 3.25rem;
  }
  
  .settings-title {
    font-size: 1.625rem;
    margin-bottom: 2.5rem;
  }
  
  .form-actions {
    margin-top: 2.25rem;
  }
}
@media (min-width: 1601px) and (max-width: 1750px) {

 :deep(.el-form-item__label) {
    font-size: 0.95rem !important;
    padding-bottom: 0.55rem;
  }
  
  :deep(.el-input__inner) {
    font-size: 0.95rem !important;
  }
  
  .avatar-hint {
    font-size: 0.85rem;
  }
  
  .form-actions .el-button {
    font-size: 0.95rem;
  }


  .user-settings-container {
    max-width: 640px;
    min-height: calc(100vh - 4rem);
    margin: 2rem auto;
  }
  
  .settings-card {
    padding: 2.5rem;
  }

  .avatar-wrapper {
    width: 8rem;
    height: 8rem;
    margin-bottom: 1rem;
  }
  
  .avatar-edit {
    width: 2.75rem;
    height: 2.75rem;
  }
  
  .settings-title {
    font-size: 1.375rem;
    margin-bottom: 1.75rem;
  }
}


/* 针对不同屏幕尺寸的优化 */
@media (max-width: 1600px) {
  .user-settings-container {
    max-width: 600px;
  }
  
  .settings-card {
    padding: 2rem;
  }
}

@media (max-width: 1440px) {
  .avatar-wrapper {
    width: 7rem;
    height: 7rem;
  }
  
  .avatar-edit {
    width: 2.25rem;
    height: 2.25rem;
  }
}

@media (max-width: 1280px) {
  .user-settings-container {
    max-width: 560px;
    padding: 0 1.5rem;
  }
  
  .settings-card {
    padding: 1.75rem;
  }
  
  .settings-title {
    font-size: 1.375rem;
  }
  
  .form-actions {
    gap: 1rem;
  }
}

@media (max-width: 1024px) {
  .user-settings-container {
    max-width: 520px;
  }
  
  .avatar-wrapper {
    width: 6.5rem;
    height: 6.5rem;
  }
  
  .submit-btn {
    min-width: 7rem;
    height: 2.5rem;
  }
}
</style>